import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Timer;
import java.util.TimerTask;

class  MyTimerTask implements Comparable<MyTimerTask>{
    private   Runnable runnable;
    private long time;
    public MyTimerTask(Runnable runnable,long delay){
        this.runnable=runnable;
        this.time=System.currentTimeMillis()+delay;
    }
    public long gettime(){
        return time;
    }
    public Runnable getrun(){
        return runnable;
    }

    @Override
    public int compareTo(MyTimerTask o) {
        return (int) (this.time-o.time);
    }
}
public class MyTimer {
    private PriorityQueue<MyTimerTask> queue=new PriorityQueue<>();
    Object locker=new Object();

   public void schedule(Runnable runnable,long time ){
       synchronized (locker){
           queue.offer(new MyTimerTask(runnable,time));
           locker.notify();
       }
   }
   public MyTimer(){
       Thread t=new Thread(()->{
           while (true){
           try {
               synchronized (locker){
                   while (queue.isEmpty()){
                        locker.wait();
                   }
                   MyTimerTask task= queue.peek();
                   long curenttime=System.currentTimeMillis();
                   if (curenttime>=task.gettime()){
                       task.getrun().run();
                       queue.poll();
                   }else {
                       locker.wait(task.gettime()-curenttime);
                   }
               }
           }catch (InterruptedException e){
               e.printStackTrace();
             }
           }
       });
       t.start();
   }
}
class M{
    public static void main(String[] args) {
        MyTimer myTimer=new MyTimer();
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("3000");
            }
        },3000);
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("2000");
            }
        },2000);
        System.out.println("开始");
    }

}
